/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="alarm-piece-wrap">
        <div class="inner-father" @click="_clickPiece">
            <!-- eslint-disable-next-line -->
            <div v-if="renderer" v-html="centerText" class="center-text"></div>
            <div v-else class="center-text">
                <div><span class="branch-num">{{checkBranchNum}}</span><lang>个</lang></div>
            </div>
            <canvas class="alarm-circle" ref="canvas" :width="width" :height="width">
                <lang>您的浏览器不支持HTML5，请尝试其他浏览器！</lang>
            </canvas>
        </div>
        <slot></slot>
    </div>

</template>
<style>
    .branch-num{
        font-size: 30px;
        font-weight: bold;
    }
    .center-text{
        position: absolute; left: 50%; top: 50%;
        transform: translate(-50%, -50%);
        line-height: 24px;
        font-size: 14px;
    }
    .bottom-text{
        font-size: 14px;
        text-align: center;
        margin-top: 16px;
    }
    .alarm-piece-wrap{
        display: inline-block;
        position: relative;
    }

    .inner-father{
        position: relative;
        text-align: center;
        cursor: pointer;
    }
</style>
<script lang=ts>
    /**
     * Created by ued on 2016/12/7.
     * 圆环百分比块
     */

    import uuid from 'src/util/uuid';
    import { sleep, clearSleep } from 'src/util/timer';
    import logger from 'src/util/logger';
    import { Component, Vue, Prop, Watch, Ref } from 'vue-property-decorator';

    const DUR = 20;//表示圆环运动的时间间隔
    const HUNDRED = 100;
    @Component
    export default class Piece extends Vue  {
        @Ref() canvas!: HTMLCanvasElement
        @Prop({
            type: Number,
            'default': 0
        })  percentage!: number
        @Prop({
            type: Number,
            'default': 65
        })  circleRadius!: number
        @Prop({
            type: Number,
            'default': 14
        })  circleWidth!: number
        @Prop({
            type: String,
            'default': '#000000'
        })  circleColor!: string
        @Prop({
            type: String,
            'default': '#DDEDFF'
        })  circleBgColor!: string
        @Prop({
            type: Number,
            'default': 0
        })  branchNum!: number
        @Prop({
            type: Function
        })  renderer!: Function

        //计算整个告警块的宽度
        get width () {
            let two = 2;
            return (this.circleRadius + this.circleWidth / two) * two;
        }
        get centerText () {
            return this._renderText(this.checkDataRange('branchNum', this.branchNum, 0));
        }
        get checkBranchNum () {
            return this.checkDataRange('branchNum', this.branchNum, 0);
        }

        clearAry: string[] | undefined  = void 0

        _name: string | undefined = void 0

        @Watch('percentage')
        percentageChange (newpercentage = 0, percentage = 0) {
            let sAngle = this.checkDataRange('percentage', percentage || 0, 0, HUNDRED);
            let eAngle = this.checkDataRange('percentage', newpercentage || 0, 0, HUNDRED);
            this.timer(sAngle, eAngle, DUR);
        }

        @Watch('circleColor')
        circleColorChange () {
            this.timer(this.percentage, this.percentage, DUR);
        }

        @Watch('circleBgColor')
        circleBgColorChange () {
            this.timer(this.percentage, this.percentage, DUR);
        }

        //对一个数据进行数值范围检查，若有误并调整
         checkDataRange (name: string, data: number, start: number, end?: number) {
            if (typeof data !== 'number') {
                logger.log(name + ' is not number');
            }
            if (typeof start === 'number') {
                if (data < start) {
                    logger.log(name + ' is less than ' + start);
                    return start;
                }
            }
            if (typeof end === 'number') {
                if (data > end) {
                    logger.log(name + ' is more than ' + end);
                    return end;
                }
            }
            return data;
        }

         circle (percent: number) {
            let two = 2;
            let startAngleRatio = 1.5;
            let c = this.canvas;
            let cxt = c.getContext('2d');


            //由于是加粗canvas画笔，圆心位置圆半径再加上画笔一半的宽度
            let x = this.circleRadius + this.circleWidth / two,
                y = this.circleRadius + this.circleWidth / two,
                R = this.circleRadius,
                counterclockwise = false,
                circleWidth = this.circleWidth;

            if (cxt) {
                //清空画布
                cxt.clearRect(0, 0, this.width, this.width);

                //生成圆形（底圆）
                cxt.lineWidth = circleWidth;
                cxt.strokeStyle = this.circleBgColor;
                cxt.moveTo(x, y);
                cxt.beginPath();
                cxt.arc(x, y, R, 0, Math.PI * two, counterclockwise);
                cxt.stroke();

                //生成扇形
                cxt.lineWidth = circleWidth;
                cxt.strokeStyle = this.circleColor;
                cxt.moveTo(x, y);
                cxt.beginPath();
                cxt.arc(x, y, R, Math.PI * startAngleRatio, Math.PI * startAngleRatio + Math.PI * two * percent, counterclockwise);
                cxt.stroke();
            }
        }

         timer (start: number, end: number, interval: number, add?: number | boolean) {
            let me = this;
            this._name = uuid();
            this.clearAry!.push(this._name);
            sleep(this._name, interval).then(function () {
                me.circle(start / HUNDRED);
                if (typeof add !== 'boolean') {
                    add = (start < end);
                }
                if (add) {
                    start++;
                    if (start < end + 1) {
                        me.timer(start, end, interval, add);
                    }
                } else {
                    start--;
                    if (start > end - 1) {
                        me.timer(start, end, interval, add);
                    }
                }
            });
        }

         _renderText (branchNum: number) {
            if (typeof this.renderer === 'function') {
                return this.renderer.call(this, branchNum);
            }
            return '';
        }

         _clickPiece () {
            this.$emit('click');
        }


        mounted () {
            this.clearAry = [];
            let sAngle = 0;
            let eAngle = this.checkDataRange('percentage', this.percentage, 0, HUNDRED);
            this.timer(sAngle, eAngle, DUR);
        }


        destroyed () {
            for (let i = 0; i < this.clearAry!.length; i++) {
                clearSleep(this.clearAry![i]);
            }
        }
    };

</script>
